package com.itheima.web;


import com.itheima.bean.Employee;
import com.itheima.bean.P;
import com.itheima.result.R;
import com.itheima.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RequestMapping("/employee")
@RestController
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    //使用employee类接受前端传过来的参数
    public R findById(@RequestBody Employee employee, HttpServletRequest req){
        //1.调用service层的查询方法，
        Employee e = employeeService.findById(employee);



        //2.判断返回employee是否是为空，为空则待用R的error方法，返回登录失败用户或密码错误
        if (e!=null){
            //把查询到的对象存进Session作用域，主要是记录用户访问其他页面，记录是他在操作
            HttpSession s = req.getSession();
            s.setAttribute("employee",e);
           return R.success(e);
        }else{
           return R.error("用户名或密码错误！");
        }
    }
    @PostMapping("/logout")
    //使用employee类接受前端传过来的参数
    public R findLogout(HttpSession session){
        //删除session空间
        session.invalidate();
        return R.success("退出成功！");
    }


    @PostMapping
    //接受前端传过来的json数据，并转化为employee对象
    public R add(@RequestBody Employee employee,HttpSession session){
        //1.调用Service层的添加方法
        int row = employeeService.add(employee, session);
        if (row >0){
            return R.success("添加员工成功！");
        }else {
            return R.error("添加员工失败！");
        }
    }

    @GetMapping("/page")
    public R page(HttpServletRequest rsq){
        Integer page = Integer.parseInt(rsq.getParameter("page"));
        Integer pageSize = Integer.parseInt(rsq.getParameter("pageSize"));
        String s = rsq.getParameter("name");
        System.out.println(page + "=========" + pageSize);
        //1.调用service层得分页查询得方法
        //IPage<Employee> p = employeeService.findPage(page, pageSize, s);
        P p = employeeService.findPage(page, pageSize, s);
        if (p!=null){
            return R.success(p);
        }else{
            return R.error("查询失败！");
        }
    }

    @PutMapping
    public R update(@RequestBody Employee employee,HttpSession session){
        //调用service层得方法将传过来得数据进行修改
        int row = employeeService.update(employee,session);
        if (row >0){
            return R.success("更新员工成功！");
        }else {
            return R.error("更新员工失败！");
        }
    }


}
